<template>
	<div id="paramInfo">
		<el-row style="margin-bottom: 20px;">
			<el-col :span="24" style="line-height:33px;">账号信息</el-col>
			<el-col :span="3" style="text-align: right">
				<el-input
					size="small"
					placeholder="请输入"
					suffix-icon="el-icon-search"
					v-model="like"
				/>
			</el-col>
			<el-col :span="21" style="text-align: right">
				<el-button
					size="small"
					type="primary"
					icon="el-icon-search"
					@click="getnewList"
					>查询</el-button
				>
				<el-button
					size="small"
					type="primary"
					icon="el-icon-plus"
					@click="openDialog"
					>新增</el-button
				>
			</el-col>
		</el-row>
		<Table
			:tableData="tableData"
			:tableHead="tableHead"
			:isUseSlot="false"
			:page="listQuery.page"
			:limit="listQuery.limit"
			v-loading="listLoading"
		>
			<template slot="tool" slot-scope="{ data }">
				<el-button
					style="padding:3px;"
					icon="el-icon-document"
					v-if="!data.row.disEdit"
					@click="handleEdit(data.row)"
					type="text"
					>编辑</el-button
				>
				<el-button
					style="color:red;padding:3px;"
					icon="el-icon-delete"
					v-if="!data.row.disEdit"
					@click="delet(data.row)"
					type="text"
					>删除</el-button
				>
			</template>
		</Table>
		<Pagination
			v-show="total > 0"
			:total="total"
			:page.sync="listQuery.page"
			:limit.sync="listQuery.limit"
			@pagination="getList"
		></Pagination>
		<form-tem
			:info="{ title: '账号信息', width: '70%', top: '5%' }"
			:formList="formListSend"
			@submit="submit"
			ref="formDelg"
			@onClose="onClose"
		>
			<div class="tree_wrap" style=" width: 60%; height: 300px;padding-left: 13px;">
				<select-tree
					:defaultSelect="defaultSelect"
					@handleEvent="treeHandle"
					:listData="listData"
				></select-tree>
			</div>
		</form-tem>
	</div>
</template>

<script>
import Table from "@/components/Table";
import Pagination from "@/components/Pagination"; // 分页
import {
	getAccountInfo,
	getAccountList,
	getPersonTypes,
	getEnterpriseInfos,
	getSelectRoleList,
	insertAccountInfo,
	updateAccountInfo
} from "@/api/RCIM/RCIM-systemConfig";
import { CreateTreeEnterprise } from "@/api/RCIM/RCIM-system.js";
import VForm from "@/components/luyiming/VueEleForm/index.vue";
import formTem from "@/template/form.temp";
import selectTree from "@/components/luyiming/SelectTree/index.vue";
import { cloneDeep } from "lodash";
import { deleteAccountInfo } from "@/api/RCIM/RCIM-delet";
import {
	validateFormBigerLength,
	validateFormSmallLength,
	validateFormPhone,
	validFormIdentity,
	validFormUserNameIsUse,
} from '@/utils/validateForm';
export default {
	components: {
		Table,
		Pagination,
		VForm,
		formTem,
		selectTree
	},
	data() {
		return {
			listData: [],
			like: '',
			tableData: [
				{
					userName: "xxxxx",
					role: "xxxxx",
					person: "xxxxx",
					enterprise: "xxxxx"
				}
			],
			tableHead: [
				{
					prop: "userName",
					label: "用户名",
					width: "",
					align: "center"
				},
				{
					prop: "role",
					label: "角色权限",
					width: "",
					align: "center"
				},
				{
					prop: "person",
					label: "人员",
					width: "",
					align: "center"
				},
				{
					prop: "enterprise",
					label: "所属企业",
					width: "",
					align: "center"
				},
				{
					prop: "operate",
					label: "操作",
					width: "",
					align: "center"
				}
			],
			listLoading: false,
			total: 0,
			listQuery: {
				page: 1,
				limit: 10
			},
			dialogFormVisible: false,
			formList: [
				{
					list: [
						{
							type: "input",
							width: "33%",
							label: "用户名",
							placeholder: "请输入",
							moduleKey: "userName",
							maxlength: '30',
							showWordLimit: true,
							validate: function() {
								return [
									{
										required: true,
										message: "请输入用户名",
										trigger: "blur"
									},
									{
										validator: validFormUserNameIsUse,
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "input",
							width: "33%",
							label: "密码",
							placeholder: "请输入",
							moduleKey: "password",
							showPassword: true,
							validate: function() {
								return [
									{
										required: true,
										message: "请输入密码",
										trigger: "blur"
									},
									{
										validator: validateFormBigerLength(6),
										trigger: "change"
									},
									{
										validator: validateFormSmallLength(20),
										trigger: "change"
									}
								];
							}
						},
						{
							type: "select",
							width: "33%",
							label: "角色权限",
							placeholder: "请输入",
							moduleKey: "roleId",
							fetch: getSelectRoleList,
							children: "option",
							query: {
								page: 1,
								limit: 10000
							},
							options: [],
							// validate: function() {
							// 	return [
							// 		{
							// 			required: true,
							// 			message: "请选择角色权限",
							// 			trigger: "change"
							// 		}
							// 	];
							// }
						}
					],
					title: "登录信息设置"
				},
				{
					list: [
						{
							type: "input",
							width: "33%",
							label: "姓名",
							placeholder: "请输入",
							moduleKey: "name",
							maxlength: '10',
							showWordLimit: true,
							validate: function() {
								return [
									{
										required: true,
										message: "姓名不能为空",
										trigger: "blur"
									},
								];
							}
						},
						{
							type: "input",
							width: "33%",
							label: "身份证",
							placeholder: "请输入",
							showWordLimit: true,
							maxlength: '18',
							moduleKey: "identityNum",
							validate: function() {
								return [
									{
										validator: validFormIdentity,
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "input",
							width: "33%",
							label: "手机",
							placeholder: "请输入",
							moduleKey: "mbPhone",
							validate: function() {
								return [
									{
										validator: validateFormPhone,
										trigger: "blur"
									}
								];
							}
						},
						{
							type: "select",
							label: "所属企业",
							width: "33%",
							placeholder: "请输入",
							moduleKey: "belongEntId",
							children: "option",
							filterable: true,
							fetch: getEnterpriseInfos,
							options: [],
							// validate: function() {
							// 	return [
							// 		{
							// 			required: true,
							// 			message: "所属企业不能为空",
							// 			trigger: "change"
							// 		},
							// 	];
							// }
						},
						{
							type: "select",
							label: "人员类型",
							width: "33%",
							placeholder: "请输入",
							moduleKey: "personTypeId",
							children: "option",
							fetch: getPersonTypes,
							options: [],
							// validate: function() {
							// 	return [
							// 		{
							// 			required: true,
							// 			message: "人员类型不能为空",
							// 			trigger: "change"
							// 		},
							// 	];
							// }
						}
					],
					title: "人员信息设置"
				},
				{
					list: [
						{
							width: "50%",
							label: "数据权限",
							moduleKey: "infoPerm",
							inlineMessage: true,
							validate: function() {
								return [
									{
										required: true,
										message: "数据权限不能为空",
										trigger: "blur"
									},
								];
							}
						}
					],
					title: "权限信息设置"
				}
			],
			formListSend: [],
			selectTreeNode: [],
			defaultSelect: []
		};
	},
	created() {
		this.getList();
	},
	methods: {
		/**
		 * @desc 删除数据
		 * @param {Object} row 表格行数据
		 */
		delet(row) {
			this.$confirm("确认要删除吗？")
				.then(_ => {
					deleteAccountInfo(row.id).then(res => {
						if (res.code === 200) {
							this.getList();
							return this.$message({
								type: "success",
								message: "删除成功"
							});
						}
						return this.$message({
							type: "error",
							message: "删除失败"
						});
					});
				})
				.catch(_ => {});
		},
		/**
		 * @desc 点击树回调
		 * @param {Object} value 树节点数据
		 */
		treeHandle(value) {
			console.log('value', value)
			this.selectTreeNode = value;
			this.$refs.formDelg.getFormEle()[2][0].setDefaultValue({
				infoPerm: this.selectTreeNode.length > 0 ? '1': ''
			});
		},
		/**
		 * @desc 刷新数据
		 */
		getnewList(){
			this.listQuery.page = 1
			this.getList();
		},
		/**
		 * @desc 获取数据
		 */
		async getList() {
			const { data } = await getAccountList(Object.assign({}, {keyword: this.like}, this.listQuery));
			console.log(data);
			data.templateList.forEach(item => {
				if (item.role === "系统管理员") {
					item.disEdit = true;
				}
			});
			this.tableData = data.templateList;
			this.total = data.total;
		},
		/**
		 * @desc 编辑表格数据
		 * @param {Object} row 表格行数据
		 */
		handleEdit(row) {
			this.openDialog(1);
			let values = [{}, {}, {}];

			getAccountInfo({ id: row.id }).then(res => {
				this.defaultSelect = res.data.data?.infoPerm?.split?.(",") || [];
				if(this.defaultSelect.length > 0){
					values[2]['infoPerm'] = '1';
				}else{
					values[2]['infoPerm'] = '';
				}
				console.log('this.defaultSelect',this.defaultSelect, values)
				// delete res.data.data.infoPerm;
				const first = ["userName", "password", "roleId", "id"];
				const second = ["belongEntId", "personTypeId", "name", "identityNum", "mbPhone"];
				first.forEach(v => {
					values[0][v] = res.data.data[v];
				});
				second.forEach(v => {
					values[1][v] = res.data.data[v];
				});
				this.$nextTick(() => {
					this.$refs.formDelg.getFormEle().forEach((item, ide) => {
						item[0].setDefaultValue(values[ide]);
					});
				});
				// this.$nextTick(() => {
				// 	this.$refs.formDelg.getFormEle().forEach(item => {
				// 		item[0].setDefaultValue(res.data.data);
				// 	});
				// });
			});
		},
		/**
		 * @desc 新增、编辑数据
		 * @param {Object} formData 表单数据
		 */
		submit(formData) {
			const nods = this.selectTreeNode
				.filter(item => item.type === "enterprise")
				.map(item => item.id);
			formData.infoPerm = nods.join(",") || this.defaultSelect.join(',');
			console.log(formData);
			if (formData.id) {
				delete formData.password;
				return updateAccountInfo(formData).then(res => {
					if (res.code === 200) {
						this.getList();
						this.closeDialog();
						this.selectTreeNode = [];
						return this.$message({
							type: "success",
							message: "编辑成功"
						});
					}
					return this.$message({
						type: "error",
						message: "编辑失败"
					});
				});
			}
			// 调用新增接口
			insertAccountInfo(formData).then(res => {
				if (res.code === 200) {
					this.getList();
					this.selectTreeNode = [];
					this.closeDialog();
					return this.$message({
						type: "success",
						message: "新增成功"
					});
				}
				return this.$message({
					type: "error",
					message: "新增失败"
				});
			});
		},
		/**
		 * @desc 关闭弹窗
		 */
		closeDialog() {
			this.$refs.formDelg.closeDialog();
		},
		/**
		 * @desc 关闭弹窗回调
		 */
		onClose() {
			this.defaultSelect = [];
			this.$refs.formDelg.getFormEle().forEach(item => {
				item[0].deleteKeys(["id"])
			});
		},
		/**
		 * @desc 打开弹窗
		 * @param {Number} rel 
		 */
		openDialog(rel) {
			this.formListSend = cloneDeep(this.formList);
			if (rel === 1) {
				const editForm = cloneDeep(this.formList);
				editForm[0].list.splice(0, 1, {
					type: "input",
					width: "33%",
					label: "用户名",
					placeholder: "请输入",
					moduleKey: "userName",
					maxlength: '10',
					showWordLimit: true,
					validate: function() {
						return [
							{
								required: true,
								message: "请输入用户名",
								trigger: "blur"
							},
						];
					}
				});
				editForm[0].list.splice(1, 1);
				this.formListSend = editForm;
			}
			this.$refs.formDelg.openDialog();
			CreateTreeEnterprise().then(res => {
				this.listData = res.data;
			});
		}
	}
};
</script>

<style lang="scss" scoped>
#paramInfo {
	height: calc(100vh - 144px);
	overflow: hidden;
	padding: 30px 50px;
}
</style>
